package BluetoothFileMgr.start;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothFileMgrActivity extends Activity {
	
	public static BluetoothAdapter adap = null;
	public static Context mainContext = null;
	public static ArrayList<BluetoothDevice> btDevices = new ArrayList<BluetoothDevice>();
	public static ArrayList<String> devices = new ArrayList<String>();
    
	public static BluetoothDevice btDevice;
	public static InetAddress serveraddress = null;
	
	public static String mode = new String("Bluetooth");
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainblue);
        adap=BluetoothAdapter.getDefaultAdapter();
         
        //final TextView tv = new TextView(this);
        final TextView tv = (TextView) findViewById(R.id.text);
        tv.setText("BLUETOOTH FILE MANAGER");
       
        //List
        ListView lv = (ListView) findViewById(R.id.mylist);
        final AlertDialog.Builder ipDialog = new AlertDialog.Builder(this);
        //final ArrayList<BluetoothDevice> btDevices = new ArrayList<BluetoothDevice>();
        //final ArrayList<String> devices = new ArrayList<String>();//[] { "Default" };
        
        // lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, R.id.mylist, FRUITS));
        // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, FRUITS);
        mainContext = getApplicationContext();
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, devices);
        
        	// Assign adapter to ListView
        	lv.setAdapter(adapter);
        	lv.setOnItemClickListener(new OnItemClickListener() {
        		@Override
        		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        		{	
        			btDevice = btDevices.get(position);
        			Intent myIntent = new Intent(view.getContext(), FileManager.class);
    	        	startActivityForResult(myIntent, 0);
    	        	//trial(position);
    	        	////
        			//FileSocket fileSocket = new FileSocket("ankit", btDevices.get(position));
           			//Thread t9 = new Thread(fileSocket);
           			//t9.start();
        			

        			Toast.makeText(getApplicationContext(), "Click ListItem Number " + position+ " " + devices.get(position), Toast.LENGTH_LONG).show();
        			adap.cancelDiscovery();
        			//DeviceConnect dc = new DeviceConnect(btDevices.get(position), adap, getApplicationContext());
        			
        		}
        		
        		/*public void trial(int position) //throws Exception
        		{
        			BluetoothSocket fileSock = null;
        			toastMessage("FileOP", Toast.LENGTH_LONG);
                	//FileSocket fileSocket = new FileSocket(dirs.get(position));
           			//Thread t9 = new Thread(fileSocket);
           			//t9.start();
                	BluetoothSocket tmp = null;
        	    	 try {
        	             fileSock = btDevices.get(position).createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
        	             tv.setText("before conn");
        	             fileSock.connect();
        	             tv.setText("after conn");
        	             //BluetoothFileMgrActivity.adap.cancelDiscovery();
        	         } catch (IOException e) {tv.setText("connect--"+e.toString()); }
        	         //fileSock = tmp;
        	        
                 	File newFile = null;
                 	FileInputStream fin = null;
 					try {
 						tv.setText("before");
 						newFile = new File(Environment.getExternalStorageDirectory().toString()+"/"+"Z_MUSIC.mp3");
 						newFile.createNewFile();
 						tv.setText(newFile.toString());
 						//File olderFile = new File(Environment.getExternalStorageDirectory().toString()+"/"+"x.jpg");
 						//fist = new FileInputStream(olderFile);
 						//byte fileContent[] = new byte[(int)olderFile.length()];
 						//fist.read(fileContent);
 						//f = new FileOutputStream(file);
 						//f = new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString()+"/"+"yournewfile.txt"));
 						//fout = new DataOutputStream(f);
 						//fout.write(fileContent);
 						//fout = new DataOutputStream(f);
 					} catch (Exception e) {
 						// TODO Auto-generated catch block
 						tv.setText(e.toString());
 						e.printStackTrace();
 					}
        	         
                	DataInputStream din = null;
                	InputStream inst = null;
        			try {
        				inst = fileSock.getInputStream();
        			} catch (IOException e){}
                    //int i = 0;
                    //while(true)
                    ///////////////////////////////////////////////////////////////
                    {	
                    	DataOutputStream dout = null;
                     	FileOutputStream fout = null;
						try {
							fout = new FileOutputStream(newFile);
							dout = new DataOutputStream(fout);
							//fout.close();
							
						} catch (FileNotFoundException e) { }                    	
                    	String st = null;
                    	byte b[] = new byte[1000];
                    	byte by;// = new byte();
                    	//FileManager.tv2.setText("before readUTF");
                    	try { 		
                    		long i = 1;
                    		while(i<=4561025)
                    		{
                   			//tv.setText(""+i);
                    		inst.read(b, 0, 1);
                    		by = b[0];
                    		dout.write(by);
                    		i++;
                    		//b = new byte[1000];
                    		}
                    		tv.setText("read");
                    		inst.close();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							tv.setText("catch of inst.read");
						}
                    	
                    	//FileManager.tv2.setText("after readUTF n before writeUTF");
                    	//if(!st.contains("::"))
                    	try {
							//fout.writeUTF(st);
                    		//dout.write(b);
                    		fout.close();
                    		dout.close();
						} catch (Exception e) { tv.setText("catch of dout.write"); }
                    	//FileManager.tv2.setText("after writeUTF");
                    	//FileManager.dirs.clear();
                    	//FileManager.type.clear();
                    }
                	////
                
        		}*/
        	});
        		

        //devices.add("ankit"); 
        
        //Buttons
        Button turnOnButton;
        turnOnButton = (Button)findViewById(R.id.turn_on);
        Button turnOffButton;
        turnOffButton = (Button)findViewById(R.id.turn_off);
        Button scanButton;
        scanButton = (Button)findViewById(R.id.scan);
        Button discButton;
        discButton = (Button)findViewById(R.id.disc);
        Button exitButton;
        exitButton = (Button)findViewById(R.id.exit);
        Button wifiButton;
        wifiButton = (Button)findViewById(R.id.wifi);
        Button wifiServerButton;
        wifiServerButton = (Button)findViewById(R.id.wifiServer);
        //Button btButton;
        /*btButton = (Button)findViewById(R.id.bt_mngr);
        btButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	//setContentView(R.layout.mainblue);
            		//toastMessage("Bluetooth", Toast.LENGTH_LONG);
            	}
           });*/
        
        //DialogBox for bluetooth off!
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.dialog_text)
            .setCancelable(false)
            .setTitle(R.string.dialog_title)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id)
                {
                	//dialog.dismiss();
                	while(!adap.isEnabled())
            			adap.enable();
                	//notify();
            		//tv.append("\nBluetooth was disabled now enabled");
                	dialog.dismiss();
                	toastMessage("Bluetooth was disabled now enabled", Toast.LENGTH_LONG);
            		/*Context context = getApplicationContext();
                    CharSequence text = "Bluetooth turned on successfully.";
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();*/
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
            }
        });
        final AlertDialog btAlert = builder.create();
        
        turnOnButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(!adap.isEnabled())
            	{	while(!adap.isEnabled())
            			adap.enable();
        			//tv.append("\nBluetooth was disabled now enabled");
            	toastMessage("Bluetooth was disabled now enabled", Toast.LENGTH_LONG);
            	}
            	else
            	{
            		//tv.append("\nBluetooth already turned on");
            		toastMessage("Bluetooth is already turned on", Toast.LENGTH_SHORT);
            	}
            }
           });
        
        turnOffButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	Intent myIntent = new Intent(v.getContext(), FileManager.class);
                startActivityForResult(myIntent, 0);
            	if(adap.isEnabled())
            	{	while(adap.isEnabled())
            			adap.disable();
            		//tv.append("\nBluetooth was on now turned off");
            		toastMessage("Bluetooth turned off", Toast.LENGTH_LONG);
            	}
            	else
            	{
            		//tv.append("\nBluetooth already turned off");
            		toastMessage("Bluetooth already turned off", Toast.LENGTH_LONG);
            	}
            }
           });
        
        exitButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	/*if(adap.isEnabled())
            	{
            		adap.disable();
            	}*/
            	finish();
            	System.exit(0);
            }
           });
        
        wifiServerButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	Thread lanServer = new LANServer(tv);
            	lanServer.start();
            }
           });
        
        wifiButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v1) {
            	final EditText input = new EditText(getApplicationContext());
            	input.setText("192.168.48.36");
    			input.setOnKeyListener(new OnKeyListener() {
    				public boolean onKey(View v, int keyCode, KeyEvent event)
    		        {
    					if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
    		            {
    						{	
    		                }
    		                return true;
    		            }
    		            return false;
    		        }
    			});
    				//ipDialog.setView(input);
    				//AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    			ipDialog.setTitle("IP Adress");
    			ipDialog.setMessage("Enter the IP of the server");
    			ipDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
     			   public void onClick(DialogInterface dialog, int which)
     			   {	
     				   String ip = input.getText().toString();
     				   mode = new String("WiFi");
     				   try {
						serveraddress = InetAddress.getByName(ip);
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
     				   Intent intent = new Intent(mainContext, FileManager.class);
     				   startActivityForResult(intent, 0);
     			   }
    			});
    			ipDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    			   public void onClick(DialogInterface dialog, int which)
    			   {	
    					  dialog.dismiss();   
    			   }
    			});
    			ipDialog.setView(input);
    			ipDialog.show();
            }
           });
        
        discButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(!adap.isEnabled())
            	{	btAlert.show();
            	}
            	if(adap.isEnabled())
            	{	//Making discoverable
            		if (!adap.isDiscovering())
            		{
                      //Context context = getApplicationContext();
                     // CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
                      //int duration = Toast.LENGTH_SHORT;
                      //Toast toast = Toast.makeText(context, text, duration);
                      //toast.show();
                      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                      startActivityForResult(enableBtIntent,0);
                      Thread btServer = new BluetoothServer(adap, mainContext, tv);
                      btServer.start();
            		}
            	}
            }
           });
        
        BroadcastReceiver mReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //String str="";
            //tv.append("onReceive");
            if(BluetoothDevice.ACTION_FOUND.equals(action)) 
            {     // Get the BluetoothDevice object from the Intent
                   BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                   // Add the name and address to an array adapter to show in a ListView
                   //str+=device.getName() + "\n";
                   devices.add(device.getName());
                   btDevices.add(device);
                   adapter.notifyDataSetChanged();
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            {
            	//tv.append("\nDiscovery Finished");
            	toastMessage("Discovery finished", Toast.LENGTH_SHORT);
                   	//adap.startDiscovery();
            }
            //tv.append(str);
            }};
            IntentFilter found=new IntentFilter(BluetoothDevice.ACTION_FOUND);
            IntentFilter found2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            IntentFilter found3=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
       	    registerReceiver(mReceiver,found);
          	registerReceiver(mReceiver,found2);
          	registerReceiver(mReceiver,found3);
        
        scanButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	/*found=new IntentFilter(BluetoothDevice.ACTION_FOUND);
                found2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
                found3=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);*/
           	    /*registerReceiver(mReceiver,found);
              	registerReceiver(mReceiver,found2);
              	registerReceiver(mReceiver,found3);*/
            	if(!adap.isEnabled())
            	{	btAlert.show();
            	}
              	if(adap.isEnabled())
              	{
              		//tv.append("\nScanning");
              		while(adap.isDiscovering())
              		{
              		}
              		
              	}
              		toastMessage("Scanning", Toast.LENGTH_LONG);
              		devices.clear();
              		btDevices.clear();
              		Set<BluetoothDevice> pairedDevices = adap.getBondedDevices();
              		// If there are paired devices
              		if (pairedDevices.size() > 0) {
              	    // Loop through paired devices
              	    for (BluetoothDevice device : pairedDevices) {
              	        // Add the name and address to an array adapter to show in a ListView
              	    	btDevices.add(device);
              	        devices.add(device.getName());
              	    }
              		adapter.notifyDataSetChanged();
                	adap.startDiscovery();	
              	}
            }
           });
        
        if(adap!=null)
        {
        	if(!adap.isEnabled())
        	{        		
        		btAlert.show();        		
        		//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        		//startActivityForResult(enableBtIntent, 0);
        	}
        	else
        	{
        		adap.disable();
        		while(!adap.isEnabled())
        		{
        			adap.enable();
        		}
        		//tv.append("\nAlready Enabled");
        		toastMessage("Bluetooth already turned on", Toast.LENGTH_LONG);
        	}
        	/*Intent in=new Intent(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        	startActivityForResult(in,0);*/
        }
        else
        {	//tv.setText("Disabled");
        	toastMessage("Bluetooth feature not available", Toast.LENGTH_LONG);
        }
    }
    
    //Toast Message
    public void toastMessage(CharSequence text, int duration)
    {
    	Context context = getApplicationContext();
        //text = "Bluetooth turned on successfully.";
        //duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}